'''
自定义 Exception Handlers

假设有一个自定义异常 UnicornException
希望使用 FastAPI 全局处理此异常
可以使用 @app.exception_handler() 添加自定义异常处理程序
'''


import uvicorn
from fastapi import FastAPI, HTTPException, status, Request
from fastapi.responses import JSONResponse


app = FastAPI()

class UnicornException(Exception):
    def __init__(self, name:str):
        self.name = name

@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=status.HTTP_418_IM_A_TEAPOT,
        content={"message": f"Oops! {exc.name} did something. "}
    )


@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"unicorn_name": name}

'''
    如果请求 /unicorns/yolo，将会抛出 UnicornException，但它将由 unicorn_exception_handler 处理
'''

if __name__ == "__main__":
    uvicorn.run(app="main3:app", host="127.0.0.1", port=8000, reload=True, debug=True)